<template>
  <view v-if="showInfo" class="backShadow" @click.self="closePopup">
    <view class="sku_goods-content" :class="{ animated: showInfo && !slideOut, 'slide-out': slideOut }">
      <view class="info_app" @click.stop>
        <view class="sku_container" :style="skuBoxStyle">
          <view class="sku_modal">
            <view class="sku_header">
              <text class="sku_title">请选择商品规格</text>
              <text class="sku_close-btn" @click="closePopup">×</text>
            </view>
            <view class="sku_product-info">
              <image class="sku_product-image" :src="displayImage"></image>
              <view class="sku_product-details">
                <text class="sku_product-name">{{ goodsinfo.goods_name }}</text>
                <view class="sku_tags" >
                  <text class="sku_tag">{{ goodsinfo.subheading }}</text>
                </view>
                <view class="choose-sku-price-box">
                  <view class="choose-sku-price-title">单价</view>
                  <view style="margin-top: -3px">
                    <!-- <view class="choose-sku-price flex-cn" v-if="showPlusPrice(goodsinfo)" style="font-size: 30rpx;">
                      <text class="plus-price-color">￥{{ goodsinfo.plus_price }}</text>
                      <text class="plus-price-icon">PLUS</text>
                    </view>
                    <view class="choose-sku-price flex-cn" v-if="showVipPrice(goodsinfo)" style="font-size: 30rpx;">
                      <text class="price-color">￥{{ goodsinfo.shop_mem_price }}</text>
                      <text class="vip-price-icon">VIP</text>
                    </view> -->
                    <view v-if="showOnlinePrice(goodsinfo)">
                      <text class="choose-sku-price sku_price">￥{{ online_price }}</text>
                    </view>
                    <view class=" flex-cn" v-if="rebate >0">
                      <view class="temperature-box">
                          {{ rebate }}<text style="letter-spacing: 2rpx;margin-left: 2rpx;">福气值</text>
                        </view>
                      <!-- <text class="plus-price-color">￥</text>
                      <text class="plus-price-color" style="font-size: 22rpx;"> {{rebate}}</text>
                      <text class="plus-price-icon" style="padding: 5rpx 10rpx;">返福气值</text> -->
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="sku_size-selection">
              <text class="sku_size-title">尺寸</text>
              <view class="sku_size-options">
                <view v-for="(size, Sindex) in goodsinfo.skuDetailList" :key="Sindex" :class="[
                  'sku_size-option',
                  {
                    sku_selected: selectSkuDetailId === size.id,
                    sku_disabled: size.disabled,
                  },
                ]" @click="selectSize(size)">
                  <text v-if="size.disabled" class="sku_size-text sku_disabled-text">{{ size.name }}</text>
                  <text v-else>{{ size.name }}</text>
                  <text v-if="size.disabled" class="sku_out-of-stock">缺货</text>
                </view>
              </view>
            </view>

            <view class="sku_size-options" v-if="surplus && surplus <= 10">
              <text style="font-size: 24rpx; color: red">仅剩余{{ surplus }}件</text>
            </view>

            <view class="sku_quantity-selection">
              <view style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                ">
                <text class="sku_quantity-title">数量</text>
                <view class="sku_quantity-control">
                  <text class="qh-rt-single qh-rt-a-zu4424 choose-sku-change-icon" @click.stop="jian"></text>
    
                  <input style="width: 100rpx;text-align: center;" min="1" type="number" @blur.stop="blurNum" :value="buyNum"
                    placeholder="1" placeholder-class="choose-sku-p"></input>
                  <text class="qh-rt-single qh-rt-jia1 choose-sku-change-icon" @click.stop="jia"></text>
                </view>
              </view>
            </view>

            <button class="sku_add-to-cart" @click="addToCart">
              加入购物车
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>

const app = getApp().globalData;
export default {
  name: 'choose-sku',
  props: {
    goodsinfo: {
      type: Object,
      required: true,
    },
    homeIndex: {
      type: Number,
      default: 0,
    },
    BoxStyle: {
      type: Number,
      default: 0,
    },
    discount: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      // sizes: [
      //     { label: "19寸19寸19寸19寸", value: "19寸" },
      //     { label: "20寸20寸20寸", value: "20寸" },
      //     { label: "22寸20寸", value: "22寸" },
      //     { label: "24寸20寸", value: "24寸" },
      //     { label: "28寸20寸", value: "28寸", disabled: true },
      // ],
      buyNum: 1,
      showInfo: false,
      slideOut: false,
      selectSkuDetailId: null,
      stock: null, //库存
      sku_disabled: false,
      surplus: null,
      single: false,
      currentImage:null,
    };
  },

  computed: {
    displayImage() {
      if (!this.showInfo || !this.currentImage) {
        return this.goodsinfo.goods_image
      }
      return this.currentImage;
    },
    badgeText() {
      return this.$store.merShoppingGoodsList.length;
    },
    footerStyle() {
      let h = this.$store.bottomHeight + 110;
      return (
        "height:" + h + "rpx;padding-bottom:" + this.$store.bottomHeight + "rpx"
      );
    },
    skuBoxStyle() {
      if (this.BoxStyle == 0) {
        return "margin-bottom:" + (this.$store.bottomHeight + 110) + "rpx";
      } else {
        "margin-bottom:" + (this.$store.bottomHeight + 0) + "rpx";
      }
    },
    showIntegral() {
      return (
        this.$store.integral_arrive_cash == 1 &&
        this.$store.marketing_methods == 2
      );
    },
    online_price() {
      if (this.selectSkuDetailId) {
        const selectedSku = this.goodsinfo.skuDetailList.find(sku => sku.id === this.selectSkuDetailId);
        return selectedSku ? selectedSku.online_price : this.goodsinfo.online_price;
      }
      return this.goodsinfo.online_price;
    },
    rebate() {
      if (this.selectSkuDetailId) {
        const selectedSku = this.goodsinfo.skuDetailList.find(sku => sku.id === this.selectSkuDetailId);
        return selectedSku ? selectedSku.rebate : this.goodsinfo.rebate;
      }
      return this.goodsinfo.rebate;
    },
    surplus() {
      if (this.selectSkuDetailId) {
        const selectedSku = this.goodsinfo.skuDetailList.find(sku => sku.id === this.selectSkuDetailId);
        return selectedSku ? selectedSku.surplus : 0;
      }
      return 0;
    }
  },


  methods: {
    //规格
    selectSize(size) {
      console.log(size, 'size')
      if (size.goods_img) {
        this.currentImage = size.goods_img;
      } else {
        this.currentImage = this.goodsinfo.goods_img;
      }
      if (this.selectSkuDetailId != size.id) {
        this.selectSkuDetailId = size.id;
        this.surplus = size.goods_num;
      }
    },

    //多规格购物车选中的状态
    checkToCart() {
      this.$store.checkedList.push({
        goods_id: this.discount === 0 ? this.goodsinfo.id : this.goodsinfo.goods_id,
      });
      this.$store.checkedList = this.uniqueArray(
        this.$store.checkedList,
        "goods_id"
      );
    },
    // 自定义去重函数，针对对象类型的元素
    uniqueArray(arr, prop) {
      return arr.filter(
        (obj, index, self) =>
          index === self.findIndex((t) => t[prop] === obj[prop])
      );
    },

    addToCart() {
      if(!this.selectSkuDetailId ) return    uni.showToast({title: "请选择商品规格",icon: "none",});
      let index = this.$store.merShoppingGoodsList.findIndex((item) => {
        return (
          item.goods_id === this.goodsinfo.id &&
          this.selectSkuDetailId === item.sku_id
        );
      });

      if (index !== -1) {
        //更新购物车
        let Indexnum = null
        Indexnum =  Number(this.$store.merShoppingGoodsList[index].num) + Number(this.buyNum);
        let obj = {
          id: this.goodsinfo.goods_id,
          goods_id: this.goodsinfo.id,
          sku_id: this.selectSkuDetailId,
          num: Indexnum,
        };

        const status = this.$mutations.setShoppingCar(obj);
        if (status) {
          uni.showToast({
            title: "加入购物车成功",
            icon: "none",
          });
        }
      } else {
        if (!this.selectSkuDetailId && this.buyNum > 1) {
          uni.showToast({
            title: "请选择商品规格",
            icon: "none",
          });
          return;
        }
        let obj = {
          id: this.goodsinfo.goods_id,
          goods_id: this.goodsinfo.id,
          sku_id: this.selectSkuDetailId,
          num: this.buyNum,
        };
        const status = this.$mutations.setShoppingCar(obj);
        if (status) {
          uni.showToast({
            title: "加入购物车成功",
            icon: "none",
          });
        }
      }
      this.checkToCart();
      this.closePopup();

      // 加入购物车逻辑
      // let res  = null;
      // let obj = {
      //   id: this.goodsinfo.goods_id,
      //   goods_id: this.goodsinfo.id,
      //   sku_id: this.selectSkuDetailId,
      //   num: this.buyNum,
      // };

      // if (this.goodsinfo.attribute_state == 2) {
      //   if (!this.selectSkuDetailId && this.buyNum > 1) {
      //     uni.showToast({
      //       title: "请选择商品规格",
      //       icon: "none",
      //     });
      //     return;
      //   }
      //   this.handlerApply();
      //   console.log('asdas kjasijkd ')
      //   res =  this.$mutations.setShoppingCar(obj);
      //   if (res) {
      //     this.closePopup();
      //     uni.showToast({
      //       title: "成功加入购物车",
      //       icon: "none",
      //     });
      //   }
      // }

      // if (this.goodsinfo.attribute_state == 1) {
      //   this.handlerApply();
      //   res =  this.$mutations.setShoppingCar(obj);
      //   if(this.single){
      //     uni.showToast({
      //     title: "成功加入购物车",
      //     icon: "none",
      //   });
      //     this.closePopup();
      //     this.single = false
      //   }
      //   console.log(res  , 'res')
      // }
    },

    blurNum(e) {
      let num = e.detail.value;
      if (num == "" || num < 0) {
        this.buyNum = 1;
      } else {
        this.buyNum = e.detail.value;
        if (this.buyNum > 0) {
          this.single = true;
        }
      }
    },
    handlerApply() {
      this.showInfo = true;
      this.slideOut = false;
      this.surplus = null;
      this.buyNum = 1;
      this.selectSkuDetailId = null;
      this.currentImage = null; 
    },
    closePopup() {
      this.slideOut = true;
      this.surplus = null;
      this.buyNum = 0;
      this.selectSkuDetailId = null;
      this.currentImage = null;
      setTimeout(() => {
        this.showInfo = false;
        this.slideOut = false;
      }, 500); // 500ms 是动画的持续时间
    },

    decrease() {
      if (this.buyNum > 1) {
        this.$emit("update:buyNum", this.buyNum - 1);
      }
    },
    increase() {
      this.$emit("update:buyNum", this.buyNum + 1);
    },

    showSkuOnlinePrice() {
      return (
        this.goodsinfo.skuPrice &&
        !this.showSkuVipPrice() &&
        !this.showSkuPlusPrice()
      );
    },
    showSkuVipPrice() {
      return this.goodsinfo.skuShopMemPrice > 0;
    },
    showSkuPlusPrice() {
      return this.goodsinfo.skuPlusPrice > 0;
    },

    // 展示plus会员价条件
    showPlusPrice(item) {
      return app.showPlusPrice(item);
    },
    // 展示会员价条件
    showVipPrice(item) {
      return app.showVipPrice(item);
    },
    // 展示普通价格
    showOnlinePrice(item) {
      return app.showOnlinePrice(item);
    },

    // 加
    jia() {
      // if (!this.selectSkuDetailId) {
      //   uni.showToast({
      //     title: "请选择规格",
      //     icon: "none",
      //   });
      //   return;
      // }
      // if (this.buyNum >= this.surplus) {
      //   uni.showToast({
      //     title: "库存不足",
      //     icon: "none",
      //   });
      //   return;
      // } else {
      //   this.buyNum++;
      // }

      if (this.goodsinfo.attribute_state == 2) {
        if (!this.selectSkuDetailId) {
          uni.showToast({
            title: "请选择规格",
            icon: "none",
          });
          return;
        }

        if (this.buyNum >= this.surplus) {
          uni.showToast({
            title: "库存不足",
            icon: "none",
          });
          return;
        } else {
          this.buyNum++;
        }
      } else {
        if (this.buyNum >= this.goodsinfo.goods_num) {
          uni.showToast({
            title: "库存不足",
            icon: "none",
          });
          return;
        } else {
          this.single = true;
          this.buyNum++;
        }
      }
    },
    // 减
    jian() {
      if (this.buyNum > 0) {
        this.buyNum--;
      }
    },
  },
};
</script>

<style>
@import "./skuDetails.scss";

/* 下面是框的动画 */
@keyframes slideInFromBottom {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0%);
  }
}

@keyframes slideOutToBottom {
  from {
    transform: translateY(0%);
  }

  to {
    transform: translateY(100%);
  }
}

.animated {
  animation: slideInFromBottom 0.5s ease;
}

.slide-out {
  animation: slideOutToBottom 0.5s ease;
}


.temperature-box {
  background-color: #C39646;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
	color: #FFFFFF;            /* 白色文字 */
	font-size: 20rpx;          /* 文字大小 */
  margin-top: 16rpx;
  height: 28rpx;
  text-align: center;
  padding: 5rpx;
  line-height: 28rpx;
  }

.backShadow {
  width: 100%;
  height: 100%;
  /* background-color: rgba(0, 0, 0, 0.5); */
  background-color: rgba(0, 0, 0, 0.3);
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 99;
}

.sku_goods-content {
  background-color: white;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  /* padding: 20px; */
  border-radius: 8px 8px 0 0;
}

.sku-container {
  /* display: flex; */
  /* justify-content: space-around; */
  /* flex-wrap: wrap; */
  gap: 15rpx;
  align-items: center;
  padding: 10rpx;
}

.sku-button {
  flex: 1 0 auto;
  /* max-width: 60px;  */
  /* height: 30px; */
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  background-color: #f5f5f5;
  color: #000;
  font-size: 14px;
  cursor: pointer;
}

.sku-button.sku-selected {
  border: 1rpx solid #ffa500;
  background-color: #fff3e0;
  color: #ffa500;
}

.sku-button.sku-disabled {
  background-color: #e0e0e0;
  color: #a0a0a0;
  cursor: not-allowed;
}
</style>